package org.NooLab.texx;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.NooLab.utilities.datatypes.ValuePair;
import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.strings.ArrUtilities;
import org.NooLab.utilities.strings.StringsUtil;

import com.jamesmurty.utils.XMLBuilder;


import org.NooLab.texx.app.up.TexxStartup;
import org.NooLab.texx.data.VariableSettingsHandlerIntf;
import org.NooLab.texx.plugg.TexxXMLHelper;
import org.NooLab.texx.plugg.algo.externals.AlgorithmPluginsLoader;
import org.NooLab.texx.properties.PersistenceSettings;
import org.NooLab.texx.properties.TexxProperties;
import org.NooLab.texx.util.XmlStringHandling;



/**
 * 
 * 
 *  
	 txxProperties.importTransformationParameterDefaults("standards.ini");

 * 
 */
public class TexxPropertiesHandler implements TexxPropertiesHandlerIntf{

	TexxProperties txxProperties;
	
	PersistenceSettings ps;

	VariableSettingsHandlerIntf variableSettings ;
	
	String algorithmsConfigPath ="" ;
	
	private String projectName="", dataSourceName="";
	String supervisedOnlineFolder="" ;
	int nodeCount = 3;
	int srctype = 1;
	int surrogateActivated = 0;
	
	private int numberOfSimulatedRecords;

	private int targetMode = -1;
	String startupTraceInfo ="" ; 
	
	private boolean publishAppActive = false;
	private String  publishAppBasepath = "";

	
	// ---- some helpers ----
	transient DFutils fileutil = new DFutils();
	transient StringsUtil strgutil = new StringsUtil();
	transient PrintLog out = new PrintLog(2,false);
	transient ArrUtilities arrutil = new ArrUtilities();
	transient XmlStringHandling xMsg = new XmlStringHandling() ;

	
	// ========================================================================
	public TexxPropertiesHandler( TexxProperties properties){
		txxProperties = properties;
		
		
		out.setPrefix("[Texx-init]");
	}
	// ========================================================================
	
	@Override
	public void initializeDefaults() {
		
		setPlugins( true ); // make this dynamic
		
							// this comes from the out-most application layer (user, or remote control)  
							String rootFolder = TexxStartup.getProjectBasePath(); // IniProperties.fluidSomProjectBasePath ;
							rootFolder = DFutils.createPath(rootFolder, "/") ;
							
		txxProperties.setPathToSomFluidSystemRootDir(rootFolder);	// within this dir all project base directories are located
										// sth like "D:/data/projects/"
		
		
		// data
		ps.setIncomingDataClassifyFirst(false);						// interesting for nested systems...
		
		ps.setProjectName( TexxStartup.getLastProjectName() );	// will be used also for output files
		            // sth like "bank2" , i.e. the simple name of a folder where all the project files are located 
		
		ps.setKeepPreparedData(true); 								// includes persistence of transformer model
		ps.autoSaveSomFluidModels(true);
		ps.setExportTransformModelAsEmbeddedObj(true);
		
		txxProperties.addDataSource( srctype, dataSourceName);       // if the persistence settings are available, the relative path will be used
		
							// this way we could also provide a file (or database) from an arbitrary location
							// txxProperties.addDataSource( srctype,"D:/data/projects/bank2/data/raw/bankn_d2.txt"); 
						
				
		ValuePair vp;
		// [TGS] mode = single

		
		// variableSettings.setSomModelingMode(itemstr);
		
		
		txxProperties.setGlueInstanceType(1);
		txxProperties.setMessagingActive(false) ;					    // if true, the SomFluidFactory will start the glueClient ;
		   																// the SomFluid is then accessible through messaging (see the SomController application)
		txxProperties.setglueModuleMode( 0 ) ;							// 0 = off, others: act as source, receptor, or server

		// general environment

		txxProperties.activateMultithreadedProcesses(false);
		
		// assimilateVariableSettings();
		
		
		
		
		txxProperties.setShowSomProgress( TexxProperties._TXX_DISPLAY_PROGRESS_BASIC ) ;
		
		prepareStartupTraceInfo();
	}
	
	
	@Override
	public void initializeDefaultsFromFile(String inifilename) {
		// TODO Auto-generated method stub
		
	}
	
	
	@Override
	public String checkForVariableDescriptionFile(int type) {
		
		String availableDescrFile = "" ;
		String datafolder ="" ;
		boolean rB;
		try {
		
			String filename ="", dfolder="",folder = TexxStartup.getProjectBasePath();
			
			folder = fileutil.createpath( folder, TexxStartup.getLastProjectName() ) ;
			dfolder = fileutil.createpath( folder, "data/description");
			
			if (fileutil.direxists(dfolder)==false){
				return "";
			}
		
			filename = TexxStartup.getLastDataSet() ;
			
			if ((filename.indexOf("/")<0) && (filename.indexOf("\\")<0)){
				datafolder = fileutil.createpath( folder, "data/raw");
				filename = fileutil.createpath( datafolder, filename); 
			}
			if (fileutil.fileexists(filename)){
				// bankn_d2-variables.txt
				File f= new File(filename);
				filename = f.getName();
				String ext = StringsUtil.getExtensionFromFilename(filename,1); // 0 = without dot, 1 = with dot
				int p = filename.lastIndexOf(ext) ;
				if (p>0){
					filename = filename.substring(0,p) ;
				}
				filename = filename+"-variables.txt" ;
				
				filename = fileutil.createpath( dfolder, filename);
				
				if (fileutil.fileexists(filename)){
					
					
					String fc = fileutil.readFile2String( filename) ;
					int n= strgutil.frequencyOfStrings(fc, new String[]{"[","]"}); 
					if ((n>0) && (n%2==0)){
						fc= fc.toLowerCase();
						rB = fc.indexOf("[tv")>0;
						if (rB){
							rB = fc.indexOf("[id")>0;
						}
					} else{
						// xml ?
						rB = fc.indexOf( "<?xml version=\"1.0\" encoding=\"")>=0;
						// any relevant content ? 
					}
					
					availableDescrFile = filename;
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		return availableDescrFile;
	}

	@Override
	public boolean loadVariableSettingsFromFile(String  filename) throws IOException {
		boolean rB=false;
		
		if (fileutil.fileexists(filename)==false){
			return false;
		}
		
		// check format
		
		// simplified [] format
			
		rB = loadVariableSettingsFromSimplifiedIniFile(filename);
	
		// rB = loadVariableSettingsFromXmlFile(filename);
		
		return rB ;
	}
	
	
	private boolean loadVariableSettingsFromSimplifiedIniFile(String  filename) {
	
		boolean loadingOk=false;
		String str,section, rawXmlStr="" ;
		String[] iniContent,sectionItems,lines ;
		ArrayList<String> items ;
		
		
		if (fileutil.fileexists(filename)==false){
			return false;
		}
		try {
		// check format
		
		// simplified [] format
		
		str = fileutil.readFile2String(filename) ;
		
		lines = str.split("\n");
		for (int i=0;i<lines.length;i++){
			if (lines[i].trim().indexOf(";")==0){
				lines[i]="";
			}
		}
		str = arrutil.arr2text(lines, " \n");
		
		str = strgutil.replaceAll(str, "[", "##[[");
		iniContent = str.split("(##\\[)");
		
		if (iniContent.length<=1){
			return false;
		}
		
		variableSettings = getVariableSettingsHandler();
		
		for(int i=0;i<iniContent.length;i++){
			str = iniContent[i].trim();
			
			if (str.length()==0){
				continue;
			}
			str = str.replace("]", " "); str = str.replace("[", " ");
			
			sectionItems = str.split("\n");
			
			section = sectionItems[0].trim() ;
			sectionItems[0] = "" ;
			
			//for (int s=1;s<sectionItems.length;s++)
			{
				// str = sectionItems[s];
				
				items = new ArrayList<String>( strgutil.changeArrayStyle(sectionItems) );
				items = arrutil.removeempty(items) ;
				 
				for (int k=0;k<items.size();k++){
					str = items.get(k);
					str = str.trim().replace("\r", "") ;
					items.set(k,str);
				}
				if (section.toLowerCase().contentEquals("id")){
					if (items.size()>0){
						str = items.get(0).trim().replace("\r", "") ;
						variableSettings.setIdVariable( str ) ;  
					}
				}
				if (section.toLowerCase().contentEquals("ids")){
					if (items.size()>0){
						variableSettings.setIdVariableCandidates( items );  
					}
				}
				if (section.toLowerCase().contentEquals("tv")){
					if (items.size()>0){
						variableSettings.setTargetVariable( items.get(0)) ;  
					}
				}
				if (section.toLowerCase().contentEquals("tvs")){
					if (items.size()>0){
						variableSettings.setTargetVariableCandidates( items );  
					}
				}
				
				if (section.toLowerCase().contentEquals("initial")){
					if (items.size()>0){
						variableSettings.setInitialSelection( items );
					}
				}
				
				if (section.toLowerCase().contentEquals("blacklist")){
					if (items.size()>0){
						variableSettings.setBlackListedVariables( items ) ;
					}
				}
				if (section.toLowerCase().contentEquals("whitelist")){
					if (items.size()>0){
						variableSettings.setWhiteListedVariables( items ) ;
					}
				}
				if (section.toLowerCase().contentEquals("absolute exclude")){
					if (items.size()>0){
						variableSettings.setAbsoluteExclusions( items , 1);
					}
				}
				if (section.toLowerCase().contentEquals("treatment")){
					if (items.size()>0){
						variableSettings.setTreatmentDesignVariables( items ); 
					}
				}
				if (section.toLowerCase().contentEquals("group")){
					if (items.size()>0){
						variableSettings.setGroupIndicatorDesignVariables( items ); 
					}
				}
				if (section.toLowerCase().contentEquals("tgs")){
					// target group ..
					importingTargetGroupSettings( items );
				}
			}
		} // i-> all sections in iniContent
		
		loadingOk = true;
		
		
		} catch (IOException e) {
			iniContent = new String[0];
			e.printStackTrace();
		}
		
		
		return loadingOk;
	}

	
	private void importingTargetGroupSettings(ArrayList<String> items) {
		// variableSettings
		String itemstr, groupdefStr,groupIndexLabel ;
		int ix;

		ix=0;
		
		//                              in "items" search from item 0 for "mode" where 1= <before> "=" // 2=after     
		ix = arrutil.getListItemIndexByContent( items, 0,       // list, start index
												"mode", 1, "=", // search for, 1=before, "="
												0,0);           // relaxed, inverted
		if (ix>=0){
			itemstr = items.get(ix) ;
			// mode = single
			itemstr = itemstr.replace("mode","");
			itemstr = itemstr.replace("=","").trim();
			variableSettings.setSomModelingMode(itemstr);
			 
		} // "mode" defined ?
		
		// ................
		ix = arrutil.getListItemIndexByContent( items, 0, "excludedvalues", 1, "=", 0,0);
		if (ix>=0){
			itemstr = items.get(ix) ;
			// a list of doubles...
			int p = itemstr.indexOf("=");
			if ((itemstr.length()>0) && (p>0)){
				itemstr = itemstr.substring( p+1, itemstr.length()).trim() ;
				String[] valuesStrs = itemstr.split(";") ;
				for (int n=0;n<valuesStrs.length;n++){
					if (valuesStrs[n].length()>0){
						double v = Double.parseDouble(valuesStrs[n]) ;
					}
				} // ->
			}// ?
			
		} // "excludedvalues" defined ?
		// ................

		for (int i=0;i<items.size();i++){
			itemstr = items.get(i) ;
			if (itemstr.toLowerCase().trim().startsWith("group")){  // sth like: "group.1 = intermediate: 0.53;0.72"
				String[] groupdefs =  itemstr.split("=");
				groupIndexLabel = groupdefs[0].replace("group", "").trim();
				if (groupIndexLabel.startsWith(".")){
					groupIndexLabel=groupIndexLabel.substring(1,groupIndexLabel.length()) ;
				}
				groupdefStr = groupdefs[1];
				// assimilate
				assimilateTargetGroupDefItem( groupIndexLabel , groupdefStr);
			}
			
		} // i-> all entries
	}
	
	
	private void assimilateTargetGroupDefItem(String groupIndexLabel, String groupdefStr) {
	// for entry : group.1 = intermediate: 0.53;0.72 => we get:  1  ,  intermediate: 0.53;0.72
		String tgLabel="";
		double[] values = new double[2] ;
		
		groupdefStr = groupdefStr.trim() ;
		int pdp = groupdefStr.indexOf(":");
		if (pdp>0){
			tgLabel = groupdefStr.substring(0,pdp);
			tgLabel = tgLabel.replace(":", "");
			groupdefStr = groupdefStr.substring(pdp+1,groupdefStr.length());
		}else{
			groupdefStr = groupdefStr.replace(":", "");
		}
		// now we have a pair of values: groupdefStr = 0.53;0.72
		groupdefStr = groupdefStr.trim() ;
		String[] valuesStrs = groupdefStr.split(";") ;
		
		if (valuesStrs[0].length()==0){
			valuesStrs[0]="0.5";
		}
		if (valuesStrs[1].length()==0){
			valuesStrs[1]="1.0";
		}
		
		values[0] = Double.parseDouble( valuesStrs[0].trim());
		values[1] = Double.parseDouble( valuesStrs[1].trim());
		                                    // criterionLowerLimit,criterionUpperLimit, label
		variableSettings.addSingleTargetGroupDefinition( values[0],values[1], tgLabel);
		
	}
	
	
	
	@SuppressWarnings("unused")
	private boolean loadVariableSettingsFromXmlFile(String  filename) throws IOException {

		boolean loadingOk=false;
		String str, rawXmlStr="";
		
		 
		
		
		rawXmlStr = fileutil.readFile2String(filename) ;
	 
		
		if (rawXmlStr.length()==0){
			return false;
		}
		
		xMsg.clear() ;
		xMsg.setContentRoot( "properties") ;
		
		str = xMsg.getSpecifiedInfo(rawXmlStr, "//properties", "target") ; // = "somfluid" ?
		str = xMsg.getSpecifiedInfo(rawXmlStr, "//properties", "section") ;// = "variables" ?
		
		
		
		
		// we provide a small interface for dealing with initial variable settings all at once
		VariableSettingsHandlerIntf variableSettings = getVariableSettingsHandler();
	
	    
		loadingOk = true;
		
		return loadingOk;
	}
	
	
	@Override
	public String getStartupTraceInfo() {
		 
		return startupTraceInfo;
	}

	
	/**
	 * 
	 * called after all settings have been defined
	 * creating a simple string that is used to create a "boot file": SomFluid then is able to know 
	 * about the project of the last run, in case a "resume" is requested
	 * 
	 * @return
	 */
	private void prepareStartupTraceInfo() {
		
		String cfgroot, userdir, lastproject, infoStr="";
		
		
		cfgroot =  txxProperties.getSystemRootDir() ;
		lastproject = txxProperties.getPersistenceSettings().getProjectName() ;
		
		// TODO better -> several categories: load file, modify it, write it back
		infoStr =  "cfgroot::"+cfgroot+"\n" +
		           "project::"+lastproject+"\n" ;
				                           	   

		
		startupTraceInfo = infoStr;
	}

	
	
	public void setPlugins( boolean loadNow){
		
		 
		AlgorithmPluginsLoader lap ;
		
		// loading "builtinscatalog.xml" which is necessary for global indexing and activation of built-in algorithms
		txxProperties.setAlgorithmsConfigPath( algorithmsConfigPath ); 

		// here we need an absolute path, the file is needed also for advanced auto assignments of built-in algorithms, 
		// even if there are no custom algorithms
		TexxPluginSettingsIntf plugs = txxProperties.getPluginSettings();
		plugs.setBaseFilePath(algorithmsConfigPath, "catalog.xml") ;
		// the plugin jarfiles are expected to sit in a relative sub-dir "transforms/" to this base-dir...
		
		
		String catfilename = fileutil.createpath( algorithmsConfigPath , "catalog.xml");
		if (fileutil.fileexists(catfilename)==false){
			out.printErr(1, "File <catalog.xml> not found in provided folder : \n"+
							"   "+ catfilename +"\n"+
							"...thus no plugins for transformation algorithms will be loaded!");
			loadNow=false;
		}
		String algofolder = txxProperties.getPluginSettings().getBaseFilePath();
		
		int n = fileutil.enumerateFiles( "", ".jar", algofolder) ;
		
		if ((fileutil.direxists( algofolder) ==false) || (n<=0)){
			out.printErr(1, "Catalog file has been found, yet the expected folder  \n"+
							"   "+ algofolder +"\n"+
							"does not exist, or does not contain any file."+"\n"+
							"Application will start, but later its transformation module might behave in unexpected ways");
				loadNow=false;
				txxProperties.setPluginsAvailable(false);
		}else{
			if (txxProperties.isPluginsAllowed()){
				String plur = "s" ; if (n==1)plur="" ;
				out.print(2, n+" plugin file"+plur+" found.\n") ;
			}else{
				if (loadNow==false){
					String plur = "s" ; if (n==1)plur="" ;
					out.print(2, n+" plugin file"+plur+" found, but plugins aren't allowed.\n") ;
				}
			}
		}
		
		txxProperties.setPluginsAllowed( loadNow ) ; // could be controlled form the outside in a dynamic manner
		txxProperties.setPluginsAvailable(loadNow);
		
		try {
			if (txxProperties.isPluginsAllowed()){
				lap = new AlgorithmPluginsLoader(txxProperties, true);
				if (lap.isPluginsAvailable()) {
					lap.load();
					
					if (lap.getNotLoadedJars().size()>0){
						out.printErr(2, "The following jarfiles and/or classes have not been loaded:");
						for (int i=0;i<lap.getNotLoadedJars().size();i++){
							out.printErr(2," -  "+lap.getNotLoadedJars());
						}
					}
				}
			}
			// feedback about how much plugins loaded ...
			
			//
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void setAlgorithmsConfigPath(String pathToCatalogFolder) throws Exception {

		algorithmsConfigPath = pathToCatalogFolder ; 
		
		algorithmsConfigPath = algorithmsConfigPath.trim();
		algorithmsConfigPath = strgutil.replaceAll(algorithmsConfigPath, "\\", "/");
		algorithmsConfigPath = strgutil.replaceAll(algorithmsConfigPath, "//", "/");
		
		if (fileutil.direxists( algorithmsConfigPath)==false){
			throw(new Exception("requested path does not exist : "+pathToCatalogFolder));
		}
		if (algorithmsConfigPath.endsWith("/")==false){
			algorithmsConfigPath = algorithmsConfigPath+"/"; 
		}
	}

	@Override
	public void setInstance(String description, int ...nodecount ) {
	 
		description = description.trim().toLowerCase();
		
		
		if (description.startsWith("tx")){
			txxProperties.setInstanceType() ;   
				// the main role the module is exhibiting, MANDATORY !!!
				// _SOM  _OPTIMIZER _TRANSFORM

			

		} // worker instance for default 
		
		 
		ps = txxProperties.getPersistenceSettings() ;
	}

	@Override
	public void setSomTargetMode(int targetmode) {
		
		/*
		 *   _TARGETMODE_MULTI  	requires the determination of values that define an interval for a target group
		 							a virtual column will be created which encodes these settings (by SomTransformer)
		 							
		 	 _TARGETMODE_SINGLE 	standard modeling, target groups can be translated to a binary flag: is target=preferred outcome, or not 
		*/
		
		targetMode = targetmode;
	}

	
	@Override
	public void setDataSourcing(String srcDescription, int activateOnlineMode) {
		
		srcDescription = srcDescription.trim().toLowerCase();
		
		
		if (srcDescription.startsWith("file")){
		
			srctype = TexxProperties._SRC_TYPE_FILE;			// alternatives: db (not realized), online learning on continuous stream (not realized)
			// SomFluidProperties._SRC_TYPE_XONLINE
			
			if (activateOnlineMode>0){
				String rootFolder = TexxStartup.getProjectBasePath(); // IniProperties.fluidSomProjectBasePath ;
				if (fileutil.direxists(rootFolder)==false){
					// create tmp
				}
				if (fileutil.direxists(rootFolder) ){
					String prjname = TexxStartup.getLastProjectName();
					supervisedOnlineFolder = fileutil.createpath(rootFolder, "online/incoming") ;
					ps.setIncomingDataSupervisionDir(supervisedOnlineFolder);
				}
				ps.setIncomingDataSupervisionActive(true);
				
				
			} // activateOnlineMode>0 ?
			else {
				ps.setIncomingDataSupervisionActive(false);
			}
			
		} // "file" ?

		
		
		
	}

	@Override
	public void setDataSourceName(String srcName) {
		
		dataSourceName = srcName;
	}
	

	@Override
	public void setSupervisedDirectory(String folder) throws Exception {
		
		if (srctype != TexxProperties._SRC_TYPE_FILE ){
			ps.setIncomingDataSupervisionActive(false);
			throw(new Exception("Supervising folders for online learning mode is possible only if typw of source is FILE !"));
		}
		
		ps.setIncomingDataSupervisionDir(folder);

	}


	@Override
	public String getSupervisedDirectory() {
		return ps.getIncomingDataSupervisionDir();
	}

	@Override
	public void setDataSimulationByPrototypes(int numberOfRecords) {
		
	}

	@Override
	public void setMaxNumberOfPrototypes(int n) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setMethodforInitialVariableSelection(int mode) {
	
	}

	
	@Override
	public VariableSettingsHandlerIntf getVariableSettingsHandler() {

		if (variableSettings==null){
			// variableSettings = new VariableSettingsHandler();
		}
		return variableSettings ;
	}

	@Override
	public void setSingleTargetDefinition( String level, double criterionLowerLimit, double criterionUpperLimit, String label) {
	 
		int defLevel = 0;
		
		level = level.trim().toLowerCase() ;
		if (level.length()==0)level="raw";
		

	}

	@Override
	public void preferSmallerModels(boolean flag, int preferredMinimumSize) {


	}
	
	
	@Override
	public void setOptimizerStoppingCriteria( int absoluteStepCount, double ...stoppingConstraints) {

		int explorationDepth  = -3 ; 
		int explorationLength = -3 ; // -1 = not set, -3 = auto, as soon as data are known
		double timeConstraint = -3 ; // 
		  
		
		if (stoppingConstraints!=null){
			
			
		} // stoppingConstraints = null ?
		
	}

	

	/**
	 * returns the effective result folder
	 */
	@Override
	public String setResultsPersistence(int i) {
		
		String path;
		boolean createOutFiles = i>=1;
		
		
		txxProperties.getOutputSettings().setWriteResultFiles(createOutFiles);
		
		path = txxProperties.getSystemRootDir() ;
		path = ps.getPathToSomFluidSystemRootDir();
		path = fileutil.createpath(path, ps.getProjectName()) ; // bank2\export\results
		path = fileutil.createpath(path, "export/results/") ;
		txxProperties.getOutputSettings().setResultfileOutputPath(path) ;     
				// there is a default ! ...which is based on
				// txxProperties.setPathToSomFluidSystemRootDir("D:/data/projects/");
				// and : PersistenceSettings.setProjectName("bank2");
		
		txxProperties.getOutputSettings().setResultFilenames( null); // there are defaults, but the user might set his own preferences
		
		txxProperties.getOutputSettings().setAsXml(false);           // default = false
		txxProperties.getOutputSettings().setHtmlCompatible(true) ;  // if as xml, we then will use html compatible tags
		
		txxProperties.getOutputSettings().createZipPackageFromResults(true);// default = true
		
		txxProperties.getOutputSettings().exportApplicationModel(false);    // controls exporting the file package that is necessary for applying the data to new data
		txxProperties.getOutputSettings().setIncludeDataToExportedPackages(true);  // some parameters for that export...
		txxProperties.getOutputSettings().setIncludeResultsToExportedPackages(true);
		txxProperties.getOutputSettings().setZippedExportedPackages(true);
		
		// txxProperties.sampleVariableContributionsThruTopModels( int n_models = 10 )
		// defining what should happen upon results: saving, sending, displaying, nothing

		return  txxProperties.getOutputSettings().getResultfileOutputPath();
	}
	
	@Override
	public String getResultBaseFolder() {
		return txxProperties.getOutputSettings().getResultfileOutputPath();
	}

	public void assimilateVariableSettings(){
		assimilateVariableSettings(variableSettings);
	}
	
	public void assimilateVariableSettings( VariableSettingsHandlerIntf varsettings ) {
		
		variableSettings = varsettings;
		 
		if (variableSettings==null){
			return;
		}
		// 
		String[] strings ;
		
 
	}
	
	@Override
	public void exportVariableSettings( VariableSettingsHandlerIntf variablesettings, String xfilename) {
		
		if (variablesettings!=null){
			variableSettings = variablesettings;
		}
		
		if (variableSettings==null){
			return;
		}
		// check if actually used/filled...
		
		ArrayList<String> strList;
		TexxXMLHelper xEngine = new TexxXMLHelper();
		
		XMLBuilder  builder = xEngine.getXmlBuilder( "properties" ).a("target", "somfluid").a("section","variables");
		
		String xstr, str;
		 
		try{
			
			
			// ............................................
			builder = builder.e("general")
								.e("date").a("value", "").up()
								.e("project").a("name", "").up();
			
			builder = builder.up();
			// ............................................
			
			builder = builder.e("variables");
				strList = variableSettings.getInitialSelection();
				str = xEngine.digestStringList( strList ) ;
			
				builder = builder.e("initial").a("list", str);
				
				strList = variableSettings.getBlackListedVariables();
				str = xEngine.digestStringList( strList ) ;
			
				builder = builder.e("blacklist").a("list", str);
				
				strList = variableSettings.getAbsoluteExclusions() ;
				str = xEngine.digestStringList( strList ) ;
				int mode = variableSettings.getAbsoluteExclusionsMode() ;
				
				builder = builder.e("excluded").a("list", str).a("mode", ""+mode);
				

			builder = builder.up();
			
			// ............................................

			builder = builder.e("target");
				strList = variableSettings.getTargetVariableCandidates() ;
				str = xEngine.digestStringList( strList ) ; 
				
				builder = builder.e("variable")
									.e("activetarget").a("label", variableSettings.getTargetVariable() ).up()
									.e("candidates").a("label", str).up();
				
				builder = builder.up();
				
				strList = variableSettings.getTvGroupLabels() ;
				str = xEngine.digestStringList( strList ) ; 
				
				builder = builder.e("groups")
									.e("labels").a("label", str).up()
									.e("values").a("separationvalues", "").up();
				builder = builder.up();
			
			builder = builder.up();
			// ............................................

			
			
			// ............................................

			
			
			// ............................................

			
			
			// ............................................
			xstr = xEngine.getXmlStr(builder, false);
		
			fileutil.writeFileSimple( xfilename, xstr);
			
			
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	@Override
	public void publishApplicationPackage(boolean flag, String basepath) {
		
		publishAppActive = flag ;
		publishAppBasepath = basepath ; 
	}

	@Override
	public void setBagging(int maxNodeCount, int recordsPerNode, int... maxRecordCount) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void activateGrowingOfSom(boolean flag, int maxNodeSize, double avgQuantile) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setBooleanAdaptiveSampling(boolean b) {
		// TODO Auto-generated method stub
		
	}
	

	

	
	
	
	
	
	
	
	
	
	
	
	
}
